<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Log;
use App\Jobs\SendMail;
use EasyDingTalk\Application;

class WelcomeController extends Controller
{
    public function welcome()
    {
        $quote = Inspiring::quote();
        $quotes = explode("-", $quote);
        if (count($quotes) == 2) {
            $message = trim($quotes[0]);
            $author = trim($quotes[1]);
        } else {
            $message = $quote;
            $author = "";
        }
        Log::info($message);

        SendMail::dispatch(['title' => "重要的消息提醒", 'body' => "志哥邮件是空的。哈哈"]);
        
        return view('welcome', [
            "message" => $message,
            "author" => $author
        ]);
    }

    public function redirectToDingtalkProvider()
    {
        $app = new Application([
            'corp_id' => config('dingtalk.corp_id'),
            'app_key' => config('dingtalk.app_key'),
            'app_secret' => config('dingtalk.app_secret'),
            'token' => config('dingtalk.token'),
            'aes_key' => config('dingtalk.aes_key'),
            'oauth' => [
                'default' => [
                    'client_id' => config('dingtalk.oapi_app_id'),
                    'client_secret' => config('dingtalk.oapi_app_secret'),
                    'scope' => 'snsapi_login',
                    'redirect' => config('dingtalk.oapi_redirect'),
                ],
            ]
        ]);
        return $app->oauth->use('default')->withQrConnect()->redirect();
    }

    public function dingtalkLoginCallback() 
    {
        $app = new Application([
            'corp_id' => config('dingtalk.corp_id'),
            'app_key' => config('dingtalk.app_key'),
            'app_secret' => config('dingtalk.app_secret'),
            'token' => config('dingtalk.token'),
            'aes_key' => config('dingtalk.aes_key'),
            'oauth' => [
                'default' => [
                    'client_id' => config('dingtalk.oapi_app_id'),
                    'client_secret' => config('dingtalk.oapi_app_secret'),
                    'scope' => 'snsapi_login',
                    'redirect' => config('dingtalk.oapi_redirect'),
                ],
            ]
        ]);
        $user = $app->oauth->use('default')->user();

        return view('welcome', [
            "message" => json_encode($user),
            "author" => $user['user_info']['nick']
        ]);
    }
}
